//
//  SISSHomePassengerViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/23.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHomePassengerViewController.h"
#import "SISSPassengerCell.h"
#import "SISSRecommendHouseViewController.h"
#import "SISSPassengerResourceDetailVC.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSFindPassengerResourceViewController.h"

static NSString * const passengerCellID = @"passengerCellID";
@interface SISSHomePassengerViewController ()<SISSPassengerCellDelegate>

/** 房源数组 */
@property (strong, nonatomic) NSArray<SISSPassengerResourceModel *> *passengerResourceArr;

@end

@implementation SISSHomePassengerViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 加载数据
    [self requestNewestPassengerResourceData];
    
    // 去掉系统自带底部的线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 自动行高
    self.tableView.estimatedRowHeight = 80;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSPassengerCell" bundle:nil] forCellReuseIdentifier:passengerCellID];
    
}

- (void)setCanScroll:(BOOL)canScroll {
    _canScroll = canScroll;
    self.tableView.scrollEnabled = canScroll;
}

#pragma mark - SISSPassengerCellDelegate
- (void)passengerCellRecommendButtonDidClick:(UIButton *)button {
    
    SISSPassengerCell *cell = (SISSPassengerCell *)button.nextResponder.nextResponder;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SISSPassengerResourceModel *model = self.passengerResourceArr[indexPath.row];
    
    SISSRecommendHouseViewController *vc = [[SISSRecommendHouseViewController alloc] init];
    vc.title = @"推荐房源";
    vc.abdId = model.ID;
    vc.recommendSuccessBlock = ^{
        [self requestNewestPassengerResourceData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - UITableViewDataSource
// 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWithMessage:@"没有找到相关客源！" ifNecessaryForRowCount:self.passengerResourceArr.count];
    if (self.passengerResourceArr.count > 0) {
        return self.passengerResourceArr.count + 1;
    }
    return self.passengerResourceArr.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    SISSPassengerCell *cell = [tableView dequeueReusableCellWithIdentifier:passengerCellID forIndexPath:indexPath];
    cell.delegate = self;
    
    if (indexPath.row == self.passengerResourceArr.count) {
        static NSString * const reuseID = @"ID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            UIButton *view = [[UIButton alloc] initWithFrame:cell.contentView.bounds];
            [cell.contentView addSubview:view];
            
            UIButton *button = [[UIButton alloc] init];
            [button setTitle:@"查看更多客源" forState:UIControlStateNormal];
            [button setTitleColor:COLOR(0x8998A5) forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            [button addTarget:self action:@selector(jumpToPassengerResourceList) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
            
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(cell.contentView);
            }];
        }
        
        return cell;
    }
    
    cell.passengerModel = self.passengerResourceArr[indexPath.row];
    
    return cell;
}

- (void)jumpToPassengerResourceList {
    
    SISSFindPassengerResourceViewController *vc = [[SISSFindPassengerResourceViewController alloc] init];
    vc.title = @"找客源";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
    
    SISSPassengerResourceDetailVC *vc = [[SISSPassengerResourceDetailVC alloc] init];
    vc.title = @"客源详情";
    SISSPassengerResourceModel *passengerModel = self.passengerResourceArr[indexPath.row];
    if (!passengerModel.read) {
        
        [kNetworkManager setPassengerResourceReadWithPassengerId:passengerModel.ID success:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 200) {
                NSLog(@"插入成功！");
            }
        } failed:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];
    }
    vc.passengerModel = passengerModel;
    self.passengerResourceArr[indexPath.row].read = 1;
    [self.tableView reloadData];
    [self.navigationController pushViewController:vc animated:YES];

}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0 && self.isForbiddenBlock) {
        self.isForbiddenBlock(NO);
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.row == 0 && self.isForbiddenBlock) {
        self.isForbiddenBlock(YES);
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
//    if ([self.delegate respondsToSelector:@selector(homePassengerViewDidScroll:)]) {
//        [self.delegate homePassengerViewDidScroll:scrollView.contentOffset.y];
//    }
}

/**
 加载数据
 */
- (void)requestNewestPassengerResourceData {
    
    WeakSelf
    [SISSPublicSingleton shared].isHud = YES;
    [kNetworkManager requestNewestPassengerResourceWithSuccess:^(NSArray<SISSPassengerResourceModel *> *passengerResources) {
        
        weakSelf.passengerResourceArr = passengerResources;
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            
            [weakSelf endHeaderRefresh];
        }];

    } failed:^(NSError *error) {
        [weakSelf endHeaderRefresh];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownReloadMoreData {
    
    [self requestNewestPassengerResourceData];
}


- (void)reloadMoreData {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self endfooterRefresh];
    });
}

#pragma mark - Getter & Setter

- (NSArray<SISSPassengerResourceModel *> *)passengerResourceArr {
    if (!_passengerResourceArr) {
        _passengerResourceArr = [NSArray array];
    }
    return _passengerResourceArr;
}

@end
